import base64
import time
import uuid

from odoo import api, fields, models
from ..functions.aliyun_oss_bucket import AliyunOSSBucket

SUPPORTED_IMAGE_MIMETYPES = ['image/gif', 'image/jpe', 'image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml']


class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    datas_fname = fields.Char('文件名')
    oss_name = fields.Char('oss文件名')

    def _upload_aliyun(self, vals):
        # 获取名称
        file_name = self.env.context.get('file_name') if self.env.context.get('file_name') else vals.get('name')
        vals['type'] = 'url'  # 将文件存储类型改为url
        res_model = vals['res_model'] if vals.get('res_model') else self.env.context.get('res_model')
        oss_name = res_model + '/' + time.strftime('%Y%m%d') + '/' + str(uuid.uuid1()) + file_name  # 拼接存储的文件名：表名/日期/文件名+uid

        re_result = AliyunOSSBucket(self.env).get_aliyun_oss_bucket()
        if vals.get('datas'):
            object = re_result.put_object(oss_name, base64.b64decode(vals['datas']))  # 上传阿里云，oss_name为文件名，datas是二进制数据
            if not self.env.context.get('upload'):
                # 清空附件中存储的base64数据
                vals.pop('datas', False)
        else:
            object = re_result.put_object(oss_name, vals['raw'])
            if not self.env.context.get('upload'):
                # 清空附件中存储的二进制数据
                vals.pop('raw', False)
        # 获取文件返回的url
        url = object.resp.response.url
        https_url = 'https:' + url.split(':')[-1]
        vals['oss_name'] = oss_name  # 存储保存在oss服务器中的文件名
        # 替换为新域名，变为预览的url链接
        vals['preview_url'] = https_url.replace('https://recta-main.oss-eu-central-1.aliyuncs.com', 'https://oss.palmnet.co')
        vals['url'] = https_url
        return https_url

    @api.model_create_single
    def create(self, values):
        # 判断是否开启oss功能
        if AliyunOSSBucket(self.env).get_oss_aliyun_connected():
            # 当存在数据的时候才上传阿里云
            if values.get('datas') or values.get('raw'):
                icp = self.env['ir.config_parameter'].sudo()
                selected_ir_model_ids = icp.get_param('aliyun_oss.selected_ir_model_ids')
                if selected_ir_model_ids:
                    name_list = selected_ir_model_ids.split(',')
                    if values.get('res_model') in name_list or self.env.context.get('upload'):
                        res_url = self._upload_aliyun(values)  # 上传阿里云
                        print(res_url)
        return super(IrAttachment, self).create(values)

    def write(self, vals):
        # 判断是否开启oss功能
        if AliyunOSSBucket(self.env).get_oss_aliyun_connected() and vals.get('datas'):
            if self.oss_name:
                AliyunOSSBucket(self.env).get_aliyun_oss_bucket().delete_object(self.oss_name)
            icp = self.env['ir.config_parameter'].sudo()
            selected_ir_model_ids = icp.get_param('aliyun_oss.selected_ir_model_ids')
            if selected_ir_model_ids:
                name_list = selected_ir_model_ids.split(',')
                if vals.get('res_model') in name_list or self.env.context.get('upload'):
                    res_url = self._upload_aliyun(vals)  # 上传阿里云
                    vals['url'] = res_url
        return super(IrAttachment, self).write(vals)

    def unlink(self):
        for rec in self:
            if not rec:
                return True
            # 判断是否开启oss功能
            if AliyunOSSBucket(self.env).get_oss_aliyun_connected():
                if rec.oss_name:
                    AliyunOSSBucket(self.env).get_aliyun_oss_bucket().delete_object(rec.oss_name)
            res = super(IrAttachment, rec).unlink()
            return res
